import Konva from 'konva'
import { useRef } from 'react'
import { Group, Layer, Rect, Stage } from 'react-konva'
import styles from './index.module.less'

export default function View() {
  const groupRef = useRef<Konva.Group>(null)

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Group width={50} height={50} ref={groupRef}>
          <Rect width={50} height={50} fill='yellow' />
          <Rect
            width={20}
            height={20}
            x={15}
            y={15}
            fill='red'
            draggable
            onMouseDown={e => {
              e.target.getStage().container().className = styles.crosshair
            }}
            onMouseUp={e => {
              e.target.getStage().container().className = ''
            }}
            onDragStart={e => {
              e.target.stopDrag()
              const size = groupRef.current.getClientRect()
              const pos = e.target.getStage().getPointerPosition()

              const x = pos.x - size.width / 2
              const y = pos.y - size.height / 2
              // 计算新的位置坐标，使Group的中心点对齐到鼠标指针位置（通过减去Group宽高的一半）
              groupRef.current.setAttrs({
                x,
                y
              })
              groupRef.current.startDrag()
            }}
          />
        </Group>
      </Layer>
    </Stage>
  )
}
